import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

// 扩展Request类型以包含wxapp用户信息
declare global {
  namespace Express {
    interface Request {
      wxUser?: {
        id: string;
        roles: string[];
        aud: string;
      };
    }
  }
}

// wxapp JWT密钥
const AUTH_SECRET_WXAPP = process.env.AUTH_SECRET_WXAPP || 'wxapp-secret-key-medical-2024';

// wxapp 认证中间件
export const authenticateWxAppToken = (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
      return res.status(401).json({
        success: false,
        message: 'wxapp访问令牌缺失'
      });
    }

    // 验证JWT令牌
    jwt.verify(token, AUTH_SECRET_WXAPP, (err: any, decoded: any) => {
      if (err) {
        console.error('wxapp Token验证失败:', err.message);
        return res.status(403).json({
          success: false,
          message: 'wxapp访问令牌无效或已过期'
        });
      }

      // 检查 audience
      if (decoded.aud !== 'wxapp') {
        console.error('wxapp Token audience不匹配:', decoded.aud);
        return res.status(403).json({
          success: false,
          message: 'wxapp访问令牌无效'
        });
      }

      // 将用户信息添加到请求对象
      req.wxUser = {
        id: decoded.userId,
        roles: decoded.roles || ['wx_user'],
        aud: decoded.aud
      };

      // 同时设置 req.user 以保持兼容性
      req.user = {
        id: decoded.userId,
        username: decoded.nickname || decoded.userId,
        name: decoded.nickname || decoded.userId,
        roles: decoded.roles || ['wx_user'],
        role: decoded.roles?.[0] || 'wx_user'
      };

      next();
    });
  } catch (error) {
    console.error('wxapp认证中间件错误:', error);
    return res.status(500).json({
      success: false,
      message: 'wxapp认证服务异常'
    });
  }
};

// wxapp 角色权限检查中间件
export const requireWxAppRole = (allowedRoles: string[]) => {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!req.wxUser) {
      return res.status(401).json({
        success: false,
        message: 'wxapp用户信息缺失'
      });
    }

    const userRoles = req.wxUser.roles;
    const hasPermission = allowedRoles.some(role => userRoles.includes(role));

    if (!hasPermission) {
      return res.status(403).json({
        success: false,
        message: 'wxapp权限不足'
      });
    }

    next();
  };
};